package com.java2007.hotel.utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 * @author Reckeys
 * @version V1.0
 * @date 2021/01/25
 **/
public class FileUtils {
    //文件上传
    public static String fileUpload(HttpServletRequest request) {
        try {
            //文件上传
            Part part = request.getPart("imageUrl");
            String filename = part.getSubmittedFileName();
            //判断是否有文件
            if(!"".equals(filename)) {
                //获取文件后缀
                String suffix = filename.substring(filename.lastIndexOf("."));
                //获取文件真实路径
                String imagePath = request.getSession().getServletContext().getRealPath("/file/");
                //将文件名修改成uuid
                String fileName = UuidUtils.getUuidFileName(suffix);
                File file = new File(imagePath + fileName);
                //File file = new File(imagePath, fileName);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                //将文件写入
                part.write(file.getPath());
                return fileName;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
